package cn.le.service;

import cn.le.redis.BaseRedisUtil;
import cn.le.util.WebSocketUtil;
import cn.le.vo.RedisDeviceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class DeviceDateService {

    @Autowired
    private BaseRedisUtil baseRedisUtil;

    private static final String IEMI = "imei";
    private static final String DID = "did";

    /**
     * 打开会话
     * @param session
     */
    public void onOpen(WebSocketSession session) {
        Map<String,String> map = getMap(session);
        RedisDeviceVO vo = baseRedisUtil.get(map.get(IEMI));
        if (vo == null){
            throw new RuntimeException("设备未注册");
        }
        if (vo.getId().equals(map.get(DID))){
            throw new RuntimeException("设备号错误");
        }
        WebSocketUtil.put(map.get(DID),session);
    }

    /**8
     * 关闭会话
     * @param session
     */
    public void onClose(WebSocketSession session) throws IOException {
        Map<String,String> map = getMap(session);
        WebSocketUtil.remove(map.get(DID),session);
        session.close();
    }

    /**
     * 异常处理
     * @param session
     * @param error
     */
    public void onError(WebSocketSession session, Throwable error) throws IOException {
        if (error instanceof RuntimeException){
            session.sendMessage(new TextMessage(error.getMessage()));
        }else {
            session.sendMessage(new TextMessage("系统异常"));
        }
        onClose(session);
    }

    private Map<String,String> getMap(WebSocketSession session){
        String query = session.getUri().getQuery();
        if (StringUtils.isEmpty(query)){
            throw new RuntimeException("参数错误");
        }
        String[] param = query.split("&");
        if (param.length != 2){
            throw new RuntimeException("参数错误");
        }
        Map<String,String> map = new HashMap<>();
        map.put(IEMI,param[0]);
        map.put(DID,param[1]);
        return map;
    }
}
